package com.june.junemplayer.view;

import androidx.annotation.NonNull;
import androidx.lifecycle.ViewModelStoreOwner;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.june.junemplayer.R;
import com.june.junemplayer.base.BaseActivity;
import com.june.junemplayer.controller.GlobalViewModelController;
import com.june.junemplayer.pojo.Song;
import com.june.junemplayer.service.MediaPlayerService;
import com.june.junemplayer.service.OverlayWindowService;
import com.june.junemplayer.service.OverlayWindowView;

import java.util.ArrayList;

public class LocalSongListActivity extends BaseActivity implements View.OnClickListener {

    private Context mContext;
    private GlobalViewModelController mGlobalViewModelController;
    private MediaPlayerService mMediaPlayerService;
    private OverlayWindowService mOverlayWindowService;

    private ImageView mBack;
    private ImageView mGetLocalSongs;

    private RecyclerView mLocalSongs;
    private LocalSongAdapter mLocalSongAdapter;

    private int mLastPlaying;

    @Override
    protected void initBeforeView(Bundle savedInstanceState) {
        Log.d("JuneProcedure", getTag() + "----initBeforeView");

        mContext = this;
        mGlobalViewModelController = new GlobalViewModelController((ViewModelStoreOwner) getApplication());

    }

    @Override
    protected void bindView(Bundle savedInstanceState) {
        Log.d("JuneProcedure", getTag() + "----bindView");
        Intent MediaPlayerIntent = new Intent(this, MediaPlayerService.class);
        bindService(MediaPlayerIntent, connectionMediaPlayerServiceConnection, Context.BIND_AUTO_CREATE);
        Intent OverlayIntent = new Intent(this, OverlayWindowService.class);
        bindService(OverlayIntent, connectionOverlayWindowServiceConnection, Context.BIND_AUTO_CREATE);

        mBack = findViewById(R.id.img_Back);
        mGetLocalSongs = findViewById(R.id.img_getLocalSong);
        mLocalSongs = findViewById(R.id.rv_LocalSongs);
        mLastPlaying = -1;
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        Log.d("JuneProcedure", getTag() + "----initData");

        Back(mBack);
        mGetLocalSongs.setOnClickListener(this);

        mLocalSongAdapter = new LocalSongAdapter(mGlobalViewModelController.getSongs());
        mLocalSongAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(LocalSongAdapter adapter, View view, int position) {
                Log.d("JuneProcedure", "LocalSongAdapter" + "----onClick");
                Log.d("June", "onclick" + position);

                //判断点击的是否是上一次点击的position
                //如果是，不变化
                //如果不是，切歌，刷新状态
                int invertedPosition = mLocalSongAdapter.mSongs.size() - position - 1;
                Log.d("June", "position=" + position + "invertedPosition=" + invertedPosition);
                if (mLastPlaying != invertedPosition) {


                    //当在本页面点击播放时，会更新点击与上一次播放的item
                    //非本页面的播放，不会更新，而是回到页面重新打开
//                    mLocalSongAdapter.notifyItemChanged(position);
//                    if (mLastPlaying != -1) {
//                        mLocalSongAdapter.notifyItemChanged(mLocalSongAdapter.mSongs.size() - 1 - mLastPlaying);
//                    }


                    //点击未在播放的歌曲
                    mLastPlaying = invertedPosition;
                    //通知悬浮窗
                    mOverlayWindowService.PlaySong(mLocalSongAdapter.mSongs.get(invertedPosition));
                    //切歌
                } else {
                    //点击正在播放的歌曲

                }
//                    mCurrentPosition = position;
            }
        });
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 1);
        mLocalSongs.setLayoutManager(gridLayoutManager);
        mLocalSongs.setAdapter(mLocalSongAdapter);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_local_song_list;
    }

    @Override
    protected String getTag() {
        return "LocalSongListActivity";
    }

    @Override
    public void onClick(View view) {
        Log.d("JuneProcedure", getTag() + "----onClick");
        switch (view.getId()) {
            case R.id.img_getLocalSong:
                int size = mGlobalViewModelController.getSongsFromProvider(mContext);
                if (size != 0) {
                    mLocalSongAdapter.notifyItemRangeInserted(0, size);
                }
                break;
        }
    }

    private ServiceConnection connectionMediaPlayerServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            Log.d("JuneProcedure", getTag() + "----onServiceConnect----OverlayWindowService");
            mMediaPlayerService = ((MediaPlayerService.MediaPlayerServiceBinder) iBinder).getService();
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            Log.d("JuneProcedure", getTag() + "----onServiceDisconnected----OverlayWindowService");

        }
    };
    private ServiceConnection connectionOverlayWindowServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            mOverlayWindowService = ((OverlayWindowService.OverlayWindowServiceBinder) iBinder).getService();
            Log.d("JuneProcedure", getTag() + "----onServiceConnect----OverlayWindowService");
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            Log.d("JuneProcedure", getTag() + "----onServiceDisconnected----OverlayWindowService");

        }
    };

    public Handler LocalSongListHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            return true;
        }
    });

    public interface OnItemChildClickListener {
        void onItemChildClick(LocalSongAdapter adapter, View view, int position);
    }

    private class LocalSongAdapter extends RecyclerView.Adapter<LocalSongAdapter.LocalSongViewHolder> {
        private LocalSongAdapter mAdapter;
        private ArrayList<Song> mSongs;
        private OnItemChildClickListener mOnItemChildClickListener;

        private Song mPlayingSong;

        public LocalSongAdapter(ArrayList<Song> songs) {
            mAdapter = this;
            mSongs = songs;
            mPlayingSong=mGlobalViewModelController.getPlayingSong();
        }

        @NonNull
        @Override
        public LocalSongViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(mContext).inflate(R.layout.item_song, parent, false);
            return new LocalSongViewHolder(view);
        }

        @SuppressLint("SetTextI18n")
        @Override
        public void onBindViewHolder(@NonNull LocalSongViewHolder holder, int position) {
            int invertedPosition = mSongs.size() - position - 1;
            holder.mSongTitle.setText(mSongs.get(invertedPosition).getTitle());
            holder.mSongArtist.setText(mSongs.get(invertedPosition).getArtist());
            holder.mSongOperation.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Log.d("June", "SongOperation");
                }
            });


            if (mSongs.get(invertedPosition)==mPlayingSong) {
                holder.mSongTitle.setTextColor(mContext.getColor(R.color.gold_color));
                holder.mSongArtist.setTextColor(mContext.getColor(R.color.gold_color));
            } else {
                holder.mSongTitle.setTextColor(mContext.getColor(R.color.white));
                holder.mSongArtist.setTextColor(mContext.getColor(R.color.white));
            }

            if (mOnItemChildClickListener != null) {
                holder.mView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        getOnItemChildClickListener().onItemChildClick(LocalSongAdapter.this, v, holder.getAdapterPosition());
                    }
                });
            }
        }

        public OnItemChildClickListener getOnItemChildClickListener() {
            return mOnItemChildClickListener;
        }

        public void setOnItemChildClickListener(OnItemChildClickListener listener) {
            mOnItemChildClickListener = listener;
        }

        @Override
        public int getItemCount() {
            return mSongs == null ? 0 : mSongs.size();
        }

        public class LocalSongViewHolder extends RecyclerView.ViewHolder {
            private final View mView;
            private final TextView mSongTitle;
            private final TextView mSongArtist;
            private final ImageView mSongOperation;

            public LocalSongViewHolder(View view) {
                super(view);
                mView = view;
                mSongTitle = view.findViewById(R.id.tv_SongTitle);
                mSongArtist = view.findViewById(R.id.tv_SongArtist);
                mSongOperation = view.findViewById(R.id.img_SongOperation);
            }
        }
    }
}